package com.abxh.media.audio

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Size
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.abxh.core.utils.LogUtils
import java.io.File
import java.io.IOException
import java.util.concurrent.ExecutionException


public class MainActivity : AppCompatActivity() {
    val resolution = Size(480, 640)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getPermission()
        findViewById<View>(R.id.btn_takePhoto).setOnClickListener { takePhoto() }
        findViewById<View>(R.id.record).setOnClickListener {
            startActivity(Intent(this, MediaRecordActivity::class.java))
        }

    }

    private fun initCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener({
            try {
                bindPreview(cameraProviderFuture.get(), findViewById<PreviewView>(R.id.pv_content))
            } catch (e: ExecutionException) {
                e.printStackTrace()
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        }, ContextCompat.getMainExecutor(this))
    }



    private fun bindPreview(
        processCameraProvider: ProcessCameraProvider,
        previewView: PreviewView
    ) {

        val preview = Preview.Builder().setTargetResolution(resolution).build()
        val cameraSelector =
            CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()
        processCameraProvider.unbindAll()
        preview.setSurfaceProvider(previewView.surfaceProvider)
        val camera = processCameraProvider.bindToLifecycle(this, cameraSelector, preview)
    }

    private fun takePhoto() {
        val imageCapture = ImageCapture.Builder() //优化捕获速度，可能降低图片质量
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
            .setTargetResolution(Size(640, 480))  //设置宽高比
            .build()
        val dirPath = (getExternalFilesDir("")!!.absolutePath + File.separator + "TestRecode")
        val dirFile = File(dirPath)
        if (!dirFile.exists()) {
            val mkdir = dirFile.mkdir()
            LogUtils.e("takePhoto: mkdir：$mkdir")
        }
        val file = File(dirFile, System.currentTimeMillis().toString() + ".jpg")
        if (!file.exists()) {
            try {
                val newFile = file.createNewFile()
                LogUtils.e("takePhoto: newFile：$newFile")
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        val outputFileOptions = ImageCapture.OutputFileOptions.Builder(file).build()
        ProcessCameraProvider.getInstance(this).get().bindToLifecycle(
            this,
            CameraSelector.DEFAULT_BACK_CAMERA,
            imageCapture
        )
        imageCapture.takePicture(
            outputFileOptions,
            ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    var savedUri = outputFileResults.savedUri
                    if (savedUri == null) {
                        savedUri = Uri.fromFile(file)
                    }
                    LogUtils.e("onImageSaved*****: " + file.absolutePath)
                    LogUtils.e("onImageSaved*****: " + file.length())
                    Toast.makeText(this@MainActivity, savedUri!!.path, Toast.LENGTH_SHORT).show()
                    ProcessCameraProvider.getInstance(this@MainActivity).get().unbind(imageCapture)
                }

                override fun onError(exception: ImageCaptureException) {
                    exception.printStackTrace()
                }
            })
    }

    /**
     * 获取权限
     */
    private fun getPermission() {
        if (Build.VERSION.SDK_INT > 22) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                //先判断有没有权限 ，没有就在这里进行权限的申请
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO,Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE), 0x86)
                initCamera()
            } else {
                initCamera()
            }
        } else {
            initCamera()
        }
    }
}